﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FloodFree.Common;
using FloodFree.Web.ViewModels;
using System.Web.Security;

namespace FloodFree.Web.Controllers
{
    public class HomeController : Controller
    {

        private FloodFreeContext db = new FloodFreeContext();

        private void DropCreateDatabase()
        {
            if (db.Database.Exists())
            {
                db.Database.Delete();
                db.Database.Create();
            }
            else
            {
                db.Database.Create();
            }
        }
        private void ReloadData()
        {

            State sc = new State { Name = "Santa Catarina" };

            db.States.Add(sc);

            City jlle = new City { Name = "Joinville" };
            sc.Cities.Add(jlle);

            Sensor sensor = new Sensor { 
                City = jlle, SensorUUID = "0001", 
                Address = "Rua: Santa Catarina, 1500",
                Latitude ="-26.319955",
                Longitude="-48.85501"
            };
            db.Sensors.Add(sensor);

            for (int i = 0; i < 10; i++)
            {
                SensorUpdate update = new SensorUpdate { StatusType = 1, Status = 1, Date = DateTime.Now, Sensor = sensor };
                db.SensorUpdates.Add(update);
            }

            db.SaveChanges();

            Subscription subscription = new Subscription();
            subscription.Username = "guilherme";
            subscription.SensorId = sensor.SensorId;
            subscription.StatusType = 1;
            db.Subscriptions.Add(subscription);
            db.SaveChanges();

        }

        public ActionResult Index()
        {

            //DropCreateDatabase();
            //ReloadData();

            List<State> states = db.States
                .Include("Cities")
                .OrderBy(s => s.Name)
                .ToList();

            /*
            List<City> cities = db.Cities
                .Include("State")
                .Where(c =>
                    db.Sensors
                    .Where(s => s.Updates.Count > 0)
                    .Select(s => s.SensorId)
                    .Contains(c.Id)
                    )
                .ToList();
            */

            List<City> cities = (from Sensor s in db.Sensors
                                 where s.Updates.Count > 0
                                 select s.City).Distinct().ToList();

            IndexViewModel vm = new IndexViewModel();
            vm.States = states;
            vm.Cities = cities;
            return View(vm);
        }

        public ActionResult About()
        {
            return View();
        }
    }
}
